/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package stock.utils;

import java.io.File;
import jxl.Cell;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 打开一个可修改的 Excel 文件
 * @author peter
 */
public class MExcelFile {

    private Workbook srcWorkbook = null;
    private final WritableWorkbook copy;
    private WritableSheet sheet = null;
    private File src = null;
    private File tmp = null;
    
    public MExcelFile(File file) throws Exception {
        if (!file.exists()) {
            throw new Exception("文件不存在" + file.getPath());
        }
        src = file;
        tmp = new File(System.currentTimeMillis()+"_tmp.xls");

        srcWorkbook = Workbook.getWorkbook(file);
        copy = Workbook.createWorkbook(tmp, srcWorkbook);
        sheet = copy.getSheet(0);
    }

    public void changeSheet(int i) {
        sheet = copy.getSheet(i);
    }

    public void set(int row, int col, String val) {
        WritableCell cell = sheet.getWritableCell(col, row);
        Label label = (Label) cell;
        label.setString(val);
    }

    public String get(int row, int col) {
        Cell cell = sheet.getCell(col, row);
        return cell.getContents();
    }

    public int getRows() {
        return sheet.getRows();
    }

    public int getColumns() {
        return sheet.getColumns();
    }

    public void close() throws Exception {
        copy.write();
        copy.close();
        srcWorkbook.close();

        src.delete();
        tmp.renameTo(src);
    }

}
